﻿using System;
using UnityEngine;
namespace PluginWD
{
    public class CameraRMS : MonoBehaviour
    {
        public Color hocolor = Color.red;
        RaycastHit nowHit;
        private Vector3 rotTgtPos;
        private Vector3 cameraPos0;
        private Quaternion cameraRot0;
        void Start()
        {
            rotTgtPos = transform.position;
            cameraPos0 = transform.position;
            cameraRot0 = transform.rotation;
        }

        void Update()
        {
            if (Input.GetKey(KeyCode.F))
            {
                transform.position = cameraPos0;
                transform.rotation = cameraRot0;
            }
            if (Input.GetMouseButtonDown(0))
            {
                Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
                if (Physics.Raycast(ray, out nowHit))
                {
                    rotTgtPos = nowHit.transform.position;
                    if (!nowHit.collider.gameObject.TryGetComponent<HighlightableObject>(out HighlightableObject ho))
                    {
                        nowHit.collider.gameObject.AddComponent<HighlightableObject>();
                    }
                }
            }
            if (Input.GetKey(KeyCode.Mouse0))
            {
                try
                {
                    if (nowHit.collider.gameObject.TryGetComponent<HighlightableObject>(out HighlightableObject ho))
                    {
                        ho.On(hocolor);
                    }
                }
                catch (System.Exception)
                {

                }
            }

            if (Input.GetKey(KeyCode.Mouse1))
            {
                var mouse_x = Input.GetAxis("Mouse X");
                var mouse_y = -Input.GetAxis("Mouse Y");
                transform.RotateAround(rotTgtPos, transform.up, mouse_x * 5);
                transform.RotateAround(rotTgtPos, transform.right, mouse_y * 5);
            }
            if (Input.GetKey(KeyCode.Mouse2))
            {
                var x = Input.GetAxis("Mouse X");
                var y = Input.GetAxis("Mouse Y");
                if (x != 0.0f)
                    transform.Translate(Vector3.left * x * 0.5f);
                if (y != 0.0f)
                    transform.Translate(Vector3.up * y * -0.5f);
            }
            if (Input.GetAxis("Mouse ScrollWheel") > 0)
                transform.Translate(Vector3.forward);
            if (Input.GetAxis("Mouse ScrollWheel") < 0)
                transform.Translate(-Vector3.forward);
        }
    }
}